<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import SelectChecked from '@/components/SelectChecked.vue'
import { getRoleList } from '@/api/role'
import { userAdd, getUserList, getRoles, userDelete, editApi } from '@/api/user'
import { ElMessage } from 'element-plus'
import useInstance from '@/hooks/userInstance'
import throttle from 'lodash/throttle'

const { global } = useInstance()
const searchParm = reactive({
  username: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})
//新增表单模板
const addModel = reactive({
  id: '',
  username: '',
  password: '',
  email: '',
  nickname: '',
  rePassword: '',
  roleId: ''
})
//新增弹窗开关状态
let addFormShow = ref(false)
//表单标题
let menuTitle = ref('')
const addRef = ref()
//按钮类型
const tags = ref('')
const selectRef = ref()
//角色id列表
const roleIds = ref('')

const rules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [{ required: false, message: '请输入邮箱', trigger: 'blur' }],
  nickname: [{ required: false, message: '请输入昵称', trigger: 'blur' }],
  roles: [{ required: false, message: '请选择角色', trigger: 'blur' }]
})

const resetForm = () => {
  addModel.id = ''
  addModel.username = ''
  addModel.password = ''
  addModel.email = ''
  addModel.nickname = ''
  addModel.rePassword = ''
  addModel.roleId = ''
  nextTick(() => {
    selectRef.value.clear()
  })
}

const submitForm = () => {
  addRef.value.validate(async valid => {
    if (valid) {
      if (tags.value === '0') {
        await userAdd(addModel)
        ElMessage.success('新增成功')
      } else {
        if (addModel.roleId === '') {
          ElMessage.error('请选择角色')
        } else {
          await editApi(addModel)
          ElMessage.success('修改成功')
          addFormShow.value = false
        }
      }
    } else {
      ElMessage.error('填写信息错误')
    }
    await getList()
  })
}
const closeForm = () => {
  addFormShow.value = false
  resetForm()
}
let options = ref([])
//角色id列表
const bindValue = ref([])
//新增按钮
const addBtn = throttle(() => {
  tags.value = '0'
  addFormShow.value = true
  menuTitle.value = '新增用户'
  resetForm()
  getSelect()
}, 1000)
//编辑按钮
const editBtn = throttle(async user => {
  tags.value = '1'
  resetForm()
  addFormShow.value = true
  menuTitle.value = '编辑用户'
  await getSelect()
  await getUserRole(user.id)
  addModel.username = user.username
  addModel.email = user.email
  addModel.nickname = user.nickname
  addModel.id = user.id
  addModel.password = user.password
  addModel.roleId = roleIds.value
}, 1000)
//删除按钮
const deleteBtn = throttle(async user => {
  const confirm = await global.$myConfirm('确定要删除吗？')
  let id = user.id
  if (confirm) {
    let res = await userDelete(id)
    if (res) {
      ElMessage.success('删除成功')
    }
    await getList()
  }
}, 1000)
//搜索按钮
const searchBtn = throttle(() => {
  getList()
}, 2000)
//重置按钮
const resetBtn = throttle(() => {
  searchParm.username = ''
  searchParm.currentPage = 1
  getList()
}, 2000)
//角色选择框
const selected = value => {
  addModel.roleId = value.join(',')
}
//查询角色下拉信息
const getSelect = async () => {
  let res = await getRoleList()
  options.value = res.data
}
//表格数据
const tableList = ref([])

//查询用户信息
const getList = async () => {
  let res = await getUserList(searchParm)
  console.log(res)
  tableList.value = res.data
  searchParm.total = res.data.length
}
//查询角色信息
const getUserRole = async userId => {
  let res = await getRoles(userId)
  console.log(res.data)
  bindValue.value = res.data
  roleIds.value = res.data.join(',')
}
onMounted(() => {
  getList()
  getSelect()
})
</script>

<template>
  <el-main>
    <!-- 搜索栏 -->
    <el-form :model="searchParm" :inline="true" size="default">
      <el-form-item>
        <el-input placeholder="请输入用户名" v-model="searchParm.username" />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" @click="searchBtn">查询</el-button>
        <el-button icon="Close" type="danger" plain @click="resetBtn"
          >重置</el-button
        >
        <el-button icon="Plus" type="primary" @click="addBtn">新增</el-button>
        <el-button icon="download" type="success" @click="exportExcel"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <!--表格数据-->
    <el-table :data="tableList" style="width: 100%">
      <el-table-column type="selection" min-width="5%" />
      <el-table-column prop="username" label="用户名" min-width="15%" />
      <el-table-column prop="nickname" label="昵称" min-width="15%" />
      <el-table-column prop="email" label="邮箱" min-width="15%" />
      <el-table-column label="拥有角色" min-width="20%">
        <template #default="scope">
          <!-- scope.row 是对应行的数据，即一个 Role 对象 -->
          <el-tag v-for="(role, index) in scope.row.roles" :key="role.id">
            {{ role.comment }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="15%">
        <template #default="scope">
          <el-button
            link
            type="success"
            icon="Edit"
            size="small"
            @click="editBtn(scope.row)"
            :disabled="scope.row.username === '55555'"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            size="small"
            @click="deleteBtn(scope.row)"
            :disabled="scope.row.username === '55555'"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </el-main>
  <!--  新增，编辑弹窗-->
  <el-dialog v-model="addFormShow" :title="menuTitle" width="50%">
    <el-form
      :model="addModel"
      ref="addRef"
      :rules="rules"
      label-width="120px"
      size="default"
      :inline="false"
    >
      <el-row>
        <el-col :span="10">
          <el-form-item prop="username" label="用户名：">
            <el-input v-model="addModel.username" placeholder="请输入用户名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="nickname" label="昵称：">
            <el-input v-model="addModel.nickname" placeholder="请输入昵称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item prop="email" label="邮箱：">
            <el-input v-model="addModel.email" placeholder="请输入邮箱地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="roles" label="角色：">
            <select-checked
              ref="selectRef"
              :options="options"
              :bindValue="bindValue"
              @selected="selected"
            ></select-checked>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item prop="password" label="密码：">
            <el-input v-model="addModel.password" placeholder="请输入密码" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeForm">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
